# coding:utf8

from appserver import db_store
from sqlalchemy import  or_
from models.entity.tree_model_base import TreeModelBase

"""
模块数据模型分类
"""


class DictCategory(TreeModelBase):
    __tablename__ = "dcit_categorys"
    __bind_key__ = "main"

    # autoincrement=True,
    id = db_store.Column(db_store.Integer, primary_key=True, comment=u'字典分类编号')
    name = db_store.Column(db_store.String(64), nullable=False, unique=True, comment=u'分类名称')
    code = db_store.Column(db_store.String(32), nullable=False, unique=True, comment=u"模块编码")
    description = db_store.Column(db_store.String(255), comment=u"描述")
    parent_id = db_store.Column(db_store.Integer, nullable=False, comment=u"父ID")
    path = db_store.Column(db_store.String(255), nullable=False, comment=u"路径")
    depth = db_store.Column(db_store.Integer, comment=u"深度")
    child_num = db_store.Column(db_store.Integer, comment=u"子类数量")
    dis_order = db_store.Column(db_store.Integer, comment=u"排序")
    status = db_store.Column(db_store.Integer, comment=u"状态")  # 0-正常 1-禁用
    dicts = db_store.relationship('Dict', backref='dict', lazy='dynamic')

    def __repr__(self):
        return "<DictCategory %s>" % self.name

    @staticmethod
    def get_dict_category_all():
        return DictCategory.query.all()

    @staticmethod
    def get_dict_category_by_id(id_num):
        return DictCategory.query.filter_by(id=id_num).first()

    @staticmethod
    def get_dict_category_by_name(name):
        return DictCategory.query.filter_by(name=name).first()

    @staticmethod
    def get_dict_category_by_code(code):
        return DictCategory.query.filter_by(code=code).first()

    @staticmethod
    def get_dict_categorys_by_parent_id(parent_id):
        return DictCategory.query.filter_by(parent_id=parent_id).all()

    @staticmethod
    def search(query_word):
        data = []
        buttons = DictCategory.query.filter(
            or_(DictCategory.code.like('%' + query_word + '%'), DictCategory.name.like('%' + query_word + '%'),
                DictCategory.description.like('%' + query_word + '%'))).all()
        for obj in buttons:
            data.append(obj.to_dict())
        return data